import { Input, Modal } from "antd";
import * as LucideIcon from "lucide-react";
import { icons } from "lucide-react";
import { useEffect, useState } from "react";
import { cn } from "~/utils/ui.util";

const iconList = Object.keys(icons);

interface Props {
  value?: string;
  onChange?: (value: string) => void;
}

export default function IconGridSelector(props: Props) {
  const [visible, setVisible] = useState(false);
  const [selectedIcon, setSelectedIcon] = useState<string>(props.value || "");

  const _ui = {
    selectIcon: () => {
      const temp: any = {
        icon: LucideIcon[selectedIcon as keyof typeof LucideIcon],
      };
      return temp.icon && <temp.icon size={18} />;
    },
  };

  useEffect(() => {
    setSelectedIcon(props.value || "");
  }, [props.value]);

  return (
    <>
      <div
        className="flex h-10 w-10 items-center justify-center rounded-md border border-gray-200"
        onClick={() => setVisible(true)}
      >
        {selectedIcon && typeof selectedIcon !== "function" && _ui.selectIcon()}
      </div>
      <Modal
        title="选择图标"
        open={visible}
        footer={null}
        onCancel={() => {
          setVisible(false);
        }}
      >
        <div className="flex flex-col gap-4">
          <Input.Search placeholder="搜索图标" />
          <div className="flex h-[50vh] flex-wrap gap-4 overflow-auto">
            {iconList.map((item) => {
              const temp: any = {
                icon: LucideIcon[item as keyof typeof LucideIcon],
              };
              return (
                <div
                  key={item}
                  className={cn(
                    "flex h-25 w-25 items-center justify-center hover:bg-gray-200 flex-col",
                    {
                      "bg-gray-200": `${item}Icon` === selectedIcon,
                    },
                  )}
                  onClick={() => {
                    props.onChange?.(item);
                  }}
                >
                  {temp.icon && typeof temp.icon !== "function" && (
                    <temp.icon size={18} />
                  )}
                  <span className=" text-xs">{item}</span>
                </div>
              );
            })}
          </div>
        </div>
      </Modal>
    </>
  );
}
